package operator.transfer;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observables.GroupedObservable;
import util.Printer;

class GroupByOperator {

    public static void main(String[] args) {
//        groupBy1();
//        groupBy2();
        groupBy3();
    }

    static void groupBy1(){
        groupBySource().subscribe(new Consumer<GroupedObservable<String, Integer>>() {
            @Override
            public void accept(GroupedObservable<String, Integer> groupedObservable) throws Exception {
                groupedObservable.subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Printer.print("key = " + groupedObservable.getKey() + " and value = " + integer);
                    }
                });
            }
        });
    }

    //前后分开
    static void groupBy2(){
        groupBySource().concatMap(new Function<GroupedObservable<String, Integer>, ObservableSource<Integer>>() {
            @Override
            public ObservableSource<Integer> apply(GroupedObservable<String, Integer> groupedObservable) throws Exception {
                return groupedObservable.flatMap(new Function<Integer, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(Integer integer) throws Exception {
                        return Observable.just(integer);
                    }
                });
            }
        }).toList().subscribe(new Consumer<List<Integer>>() {
            @Override
            public void accept(List<Integer> integers) throws Exception {
                Printer.print("list = " + integers.toString());
            }
        });
    }

    //分成不同的list
    static void groupBy3(){
        groupBySource().flatMap(new Function<GroupedObservable<String, Integer>, Observable<List<Integer>>>() {
            @Override
            public Observable<List<Integer>> apply(GroupedObservable<String, Integer> groupedObservable) throws Exception {
                return groupedObservable.toList().toObservable();
            }
        }).forEach(new Consumer<List<Integer>>() {
            @Override
            public void accept(List<Integer> integers) throws Exception {
                Printer.print("list = " + integers.toString());
            }
        });
    }

    static Observable<GroupedObservable<String, Integer>> groupBySource(){
        return Observable.range(1, 20)
                .groupBy(new Function<Integer, String>() {
                    @Override
                    public String apply(Integer integer) throws Exception {
                        return integer % 2 == 0 ? "偶数组" : "奇数组";
                    }
                });
    }


}
